<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/api.css" />
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            检测单处理
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;">
        <ul class="aui-list aui-form-list">
            <li class="aui-list-item" style="display: none;">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">检测单号</div>
                    <div class="aui-list-item-input">
                        <input type="text" id="chkBillCode" disabled="true">
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">箱号</div>
                    <div class="aui-list-item-input">
                        <input type="text" id="boxnum" disabled="true">
                    </div>
                </div>
            </li>
            <!-- <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">检测结果</div>
                    <div class="aui-list-item-input">
                        <select id="chkResult">
                        </select>
                    </div>
                </div>
            </li> -->
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">批次总数</div>
                    <div class="aui-list-item-input">
                        <input type="text" id="lotQty" disabled="true">
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">合格数量</div>
                    <div class="aui-list-item-input">
                        <input type="text" id="qualifiedQty" onblur="qualifiedQtyChange();">
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">不合格数量</div>
                    <div class="aui-list-item-input">
                        <input type="text" id="unqualifiedQty" disabled="true">
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">允许收货数量</div>
                    <div class="aui-list-item-input">
                        <input type="text" id="allowedReceiveQty" disabled="true">
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">缺陷</div>
                    <div class="aui-list-item-input">
                        <select id="qualchkitem">
                        </select>
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">业务状态</div>
                    <div class="aui-list-item-input">
                        <select id="status">
                        </select>
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">备注</div>
                    <div class="aui-list-item-input">
                        <textarea id="remark"></textarea>
                    </div>
                </div>
            </li>
            <div class="aui-content" style="background-color: #ffffff">
                <ul class="aui-list-view aui-grid-view" id="imgslist">
                    <!-- <li class='aui-list-view-cell aui-img aui-col-xs-4 aui-padded-5' style='width:150px;height:150px;' >
                        <img class='aui-img-object' src='../image/add.jpg' style='width:150px;height:150px;'>
                    </li> -->
                    <li class="aui-list-view-cell aui-img aui-col-xs-4 aui-padded-5" id="addpic" onclick="imgClick()">
                        
                        <img class="aui-img-object" src="../image/add.jpg">
                    </li>
                </ul>
            </div>
        </ul>
    </div>

    <div class='aui-btn aui-btn-info aui-btn-block' style="margin-top:10px;" onclick='save()'>保存</div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/hammer.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/clickThrottle.js"></script>
<script type="text/javascript">
    var uiMediaScanner = null;
    var imageFilter = null;
    var imageBrowser = null;
    apiready = function () {

        // 引入多选模块
        uiMediaScanner = api.require('UIMediaScanner');
        // 引入过滤压缩模块
        imageFilter = api.require("imageFilter");
        // 引入图片浏览模块
        imageBrowser = api.require('imageBrowser');

        $("#remark").val("");
        var chkBillCode = api.pageParam.chkBillCode;
        $("#chkBillCode").val(chkBillCode);

        document.getElementById("title").innerHTML = "检测单处理-" + chkBillCode;
        var boxnum=(api.pageParam.boxnum==undefined||api.pageParam.boxnum==null||api.pageParam.boxnum=="undefined")?"":api.pageParam.boxnum;
        $("#boxnum").val(boxnum);

        //查询检测结果下拉框
        doSearchChkResultList();
        //查询缺陷下拉框
        doSearchUqcqualchkitem();
        //查询业务状态下拉框
        doSearchStatus();

        //查询检测单判定结果
        doSearchChkBillChkResult();
    }

    function doSearchChkResultList(){
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getUtilComboxList";
        var data = {
            values: { ////以表单方式提交参数（JSON对象）
                tablename: "md_paraconfig",
                column_name: "paracode",
                column_value: "paraval",
                condition: " paracls='chkResult' ",
                un : un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            async:false,
            data: data
        }, function(ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var map = eval("(" + data + ")");
                var list = eval(map.list);
                var html = "";
                for (var i = 0; i < list.length; i++) {
                    html += "<option value='" + list[i].value + "'>" + list[i].label + "</option>";
                }
                $api.html($api.byId("chkResult"), html);
            }

        });
    }

    function doSearchStatus(){
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getUtilComboxList";
        var data = {
            values: { ////以表单方式提交参数（JSON对象）
                tablename: "md_paraconfig",
                column_name: "paracode",
                column_value: "paraval",
                condition: " paracls='qcChkBillMrlStatus' and paraval in('0','1','2','3','6') ",
                un : un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            async:false,
            data: data
        }, function(ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var map = eval("(" + data + ")");
                var list = eval(map.list);
                var html = "";
                for (var i = 0; i < list.length; i++) {
                    html += "<option value='" + list[i].value + "'>" + list[i].label + "</option>";
                }
                $api.html($api.byId("status"), html);
            }

        });
    }

    function doSearchUqcqualchkitem(){
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getUtilComboxList";
        var data = {
            values: { ////以表单方式提交参数（JSON对象）
                tablename: "qc_qual_chk_item",
                column_name: "name",
                column_value: "code",
                condition: " is_delete=0 ",
                un : un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            async:false,
            data: data
        }, function(ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var map = eval("(" + data + ")");
                var list = eval(map.list);
                var html = "";
                for (var i = 0; i < list.length; i++) {
                    html += "<option value='" + list[i].value + "'>" + list[i].label + "</option>";
                }
                $api.html($api.byId("qualchkitem"), html);
            }

        });
    }


    //查询检测单及物料批次信息
    function doSearchChkBillChkResult() {

        //检测单号
        var chkBillCode = $("#chkBillCode").val();

        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getChkBillChkResult";

        var data = {
            values: {
                chkBillCode: chkBillCode,
                un: un,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    var chkBill = eval(myobj.chkBill);
                        var chkResult = chkBill.chkResult;//检测结果
                        var lotQty=chkBill.lotQty;//批次总数
                        var qualifiedQty=chkBill.qualifiedQty;//合格数量
                        var unqualifiedQty=chkBill.unqualifiedQty;//不合格数量
                        var allowedReceiveQty=chkBill.allowedReceiveQty;//允许收货数量
                        var status=chkBill.status;//业务状态
                        var mrlRemark=chkBill.mrlRemark;//备注
                        var qualchkitem=chkBill.qualchkitem;//缺陷
                        $("#chkResult").val(chkResult);
                        $("#lotQty").val(lotQty);
                        $("#qualifiedQty").val(qualifiedQty);
                        $("#unqualifiedQty").val(unqualifiedQty);
                        $("#allowedReceiveQty").val(allowedReceiveQty);
                        $("#status").val(status);
                        $("#mrlRemark").val(mrlRemark);
                        $("#qualchkitem").val(qualchkitem);
                        

                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });
    }

    function qualifiedQtyChange(){
        //合格数改变后，修改不合格数量=批次总数-合格数量，允许收货数量=合格数量
        var qualifiedQty=$("#qualifiedQty").val();
        var lotQty=$("#lotQty").val();
        var unqualifiedQty=lotQty-qualifiedQty;
        var allowedReceiveQty=qualifiedQty;
        $("#unqualifiedQty").val(unqualifiedQty);
        $("#allowedReceiveQty").val(allowedReceiveQty);
    }

    function imgClick() {
        // 获取图片宽高
        var normalW = $("#addpic img").width();
        api.actionSheet({
            title: '选择图片来源',
            buttons: ['照相机', '浏览相册']
        }, function (ret, err) {
            var index = ret.buttonIndex;
            switch (index) {
                // 拍照
                case 1:
                    // 打开拍照
                    api.getPicture({
                        sourceType: "camera",
                        encodingType: "jpg",
                        destinationType: "url",
                        mediaValue: "pic",
                        quality: 50,
                        saveToPhotoAlbum: true
                    }, function (ret, err) {
                        if (ret && ret.data) {
                            // 拍照返回的本地路径
                            var returnUrl = ret.data;
                            // 图片压缩
                            imgCompress(returnUrl, 0.5, 0.5, getExt(returnUrl), function (compressImg) {
                                var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4  aui-padded-5' style='margin-left: 5px;width:" + normalW + "px;height:" + normalW + "px;' onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                    "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                // 追加图片
                                $("#addpic").before(showImgHtml);
                                // ########################################  绑定长按事件 ########################
                                addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                //上传图片
                                uploadFile(compressImg);
                            });
                        } else {
                            api.toast({
                                msg: '没有选择，或者选择出错'
                            });
                        }
                    });
                    break;
                // 打开图片选择器
                case 2:
                    uiMediaScanner.open({
                        type: 'picture',
                        column: 4,
                        classify: true,
                        max: 5,
                        sort: {
                            key: 'time',
                            order: 'desc'
                        },
                        texts: {
                            stateText: '已选*项',
                            cancelText: '取消',
                            finishText: '完成'
                        },
                        styles: {
                            bg: '#fff',
                            mark: {
                                icon: '',
                                position: 'bottom_left',
                                size: 20
                            },
                            nav: {
                                bg: '#b23e4b',
                                stateColor: '#fff',
                                stateSize: 18,
                                cancelBg: 'rgba(0,0,0,0)',
                                cancelColor: '#fff',
                                cancelSize: 18,
                                finishBg: 'rgba(0,0,0,0)',
                                finishColor: '#fff',
                                finishSize: 18
                            }
                        }
                    }, function (ret) {
                        if (ret) {
                            for (var i = 0; i < ret.list.length; i++) {
                                var selectImg = ret.list[i];
                                // 获取图片的路径
                                var selectimgPath = selectImg.path;
                                var selectimgThumbPath = selectImg.thumbPath;
                                // 图片压缩
                                imgCompress(selectimgPath, 0.5, 0.5, selectImg.suffix, function (compressImg) {
                                    var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4 aui-padded-5' style='margin-left: 5px;width:" + normalW + "px;height:" + normalW + "px;'  onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                        "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                    // 追加图片
                                    $("#addpic").before(showImgHtml);
                                    // ########################################  绑定长按事件 ########################
                                    addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                    // ################### 上传图片 #########################
                                    uploadFile(compressImg);
                                });
                            }
                        }
                    });
                    break;
            }
        });
    }

    // 图片压缩
    // imgsrc：源图片的路径
    // quality：图片压缩质量，一般建议0.5
    // scale：图片压缩比例，也是建议0.5
    // ext：源图片拓展名
    // callback：转换成功之后回调函数
    function imgCompress(imgsrc, quality, scale, ext, callback) {
        // 压缩文件的保存目录
        var savePath = api.cacheDir + "/" + getNowFormatDate() + "/";
        // 压缩文件生成的随机文件名称
        var savename = NewGuid() + "." + ext;
        imageFilter.compress({
            img: imgsrc,
            quality: quality,
            scale: quality,
            save: {
                album: false,
                imgPath: savePath,
                imgName: savename
            }
        }, function(ret, err) {
            if (ret) {
                callback(savePath + savename);
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 打开图片浏览
    // imgs：需要预览的图片集合
    function openImageBrowser(imgs) {
        imageBrowser.openImages({
            imageUrls: imgs,
            showList: false,
            activeIndex: 0
        });
    }

    // 获取当前的时间，拼接成2015-11-09这样的格式，主要用于对图片进行时间分类
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate
        return currentdate;
    }

    // 获取文件拓展名
    function getExt(fileName) {
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }

    // 生成guid,主要用于生成随机文件名
    function NewGuid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }

        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

    // 添加长按方法
    function addPress(obj, index) {
        // 获取目前长按的对象
        var hammertime = new Hammer(obj[0]);
        // 绑定长按对象
        hammertime.on("press", function(e) {
            api.confirm({
                title: '温馨提示',
                msg: '您确定要删除该图片吗？',
                buttons: ['确定', '取消']
            }, function(ret, err) {
                if (ret.buttonIndex == 1) {
                    // 移除自己
                    $(obj).remove();
                    api.toast({
                        msg: '删除成功！'
                    });
                }
            });
        });
    }

    // 上传图片
    // url：上传的url地址
    // data：上传的文件
    // callback：上传成功返回地址
    function uploadFile(data) {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/uploadPhotosAPP";
        var data = {
            values: {
                un: un
            },
            files: {
                file: data
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function(ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == "0") {
                    console.log("上传成功");
                } else if (myobj.code == "1") {
                    alert("上传失败");
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    //保存
    function save() {
        if(!clickThrottle()) return;

         //获取imgslist中所有的img，保存图片和异常业务记录的关系
         var imgs = document.getElementsByTagName('img');
        var names = [];

        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            var srcStr = img.getAttribute('src');
            var arrs = srcStr.split('\/');
            var nameStr = arrs[arrs.length - 1];
            //alert(nameStr);
            if ("add.jpg" != nameStr) {
                names[i] = nameStr;
            }
        }

        var picNames = JSON.parse(JSON.stringify(names));
        var hh=document.getElementById("addpic").innerHTML; 
        //检测单号
        var chkBillCode = $("#chkBillCode").val();
        //检测结果
        var chkResult = $("#chkResult").val();
        //合格数
        var qualifiedQty = $("#qualifiedQty").val();
        //不合格数
        var unqualifiedQty = $("#unqualifiedQty").val();
        //允许收货数
        var allowedReceiveQty = $("#allowedReceiveQty").val();
        //业务状态
        var status = $("#status").val();
        //备注
        var mrlRemark = $("#mrlRemark").val();
        //缺陷
        var qualchkitem = $("#qualchkitem").val();
         //批次总数
        var lotQty  = $("#lotQty").val();
        if(Number(qualifiedQty) + Number(unqualifiedQty) !=Number(lotQty)){
            alert("请处理检测单后再保存！");
            return;
        }
        if(status == 0){
            alert("请处理检测单后再保存！");
            return;
        }
        api.showProgress({
            title: '保存中...',
        });
        
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/chkBillSaveAc";
        var data = {
            values: {
                chkBillCode: chkBillCode,
                chkResult: chkResult,
                qualifiedQty:qualifiedQty,
                unqualifiedQty:unqualifiedQty,
                allowedReceiveQty:allowedReceiveQty,
                status:status,
                mrlRemark:mrlRemark,
                qualchkitem: qualchkitem,
                picNames: picNames,
                boxnum: api.pageParam.boxnum,
                un: un,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    api.hideProgress();
                    api.toast({
                        msg: "来料检验保存成功！",
                        duration: 3000
                    });
                    setTimeout(function(){
                      // //返回主界面，刷新表格数据
                    api.closeWin();
                    var name = api.pageParam.name;
                    api.execScript({
                        name: name,
                        script: 'reset()'
                    });
                    },2000)
                    

                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                    api.hideProgress();
                }
            } else{api.hideProgress();
                alert(JSON.stringify(err));
            }
 //           api.hideProgress();
        });
    }

    //返回按钮
    function closeWin() {
        api.closeWin({});
    }
</script>

</html>